package com.heaboy.feedback.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heaboy.databind.binding.Binder;
import com.heaboy.feedback.constant.EnumLessonStatus;
import com.heaboy.feedback.domain.*;
import com.heaboy.feedback.domain.vo.CourseClazzVO;
import com.heaboy.feedback.domain.vo.LessonVO;
import com.heaboy.feedback.domain.vo.TeacherInfoVO;
import com.heaboy.feedback.service.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.heaboy.feedback.mapper.CourseClazzMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 课程班级Service业务层处理
 * 
 * @author heaboy
 * @date 2024-02-01
 */
@Service
public class CourseClazzServiceImpl extends ServiceImpl<CourseClazzMapper, CourseClazz> implements ICourseClazzService
{
    @Autowired
    private CourseClazzMapper courseClazzMapper;
    @Autowired
    private IStudentClazzService studentClazzService;
    @Autowired
    private ICourseStudentService courseStudentService;
    @Autowired
    private ICourseService courseService;

    @Autowired
    private ILessonService lessonService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询课程班级
     * 
     * @param id 课程班级主键
     * @return 课程班级
     */
    @Override
    public CourseClazz selectCourseClazzById(Long id)
    {
        return courseClazzMapper.selectCourseClazzById(id);
    }

    /**
     * 查询课程班级列表
     * 
     * @param courseClazz 课程班级
     * @return 课程班级
     */
    @Override
    public List<CourseClazz> selectCourseClazzList(CourseClazz courseClazz)
    {
        return courseClazzMapper.selectCourseClazzList(courseClazz);
    }

    /**
     * 新增课程班级
     * 
     * @param courseClazz 课程班级
     * @return 结果
     */
    @Override
    public int insertCourseClazz(CourseClazz courseClazz)
    {
        courseClazz.setCreateTime(DateUtils.getNowDate());
        return courseClazzMapper.insertCourseClazz(courseClazz);
    }

    /**
     * 修改课程班级
     * 
     * @param courseClazz 课程班级
     * @return 结果
     */
    @Override
    public int updateCourseClazz(CourseClazz courseClazz)
    {
        courseClazz.setUpdateTime(DateUtils.getNowDate());
        return courseClazzMapper.updateCourseClazz(courseClazz);
    }

    /**
     * 批量删除课程班级
     * 
     * @param ids 需要删除的课程班级主键
     * @return 结果
     */
    @Override
    public int deleteCourseClazzByIds(Long[] ids)
    {
        return courseClazzMapper.deleteCourseClazzByIds(ids);
    }

    /**
     * 删除课程班级信息
     * 
     * @param id 课程班级主键
     * @return 结果
     */
    @Override
    public int deleteCourseClazzById(Long id)
    {
        return courseClazzMapper.deleteCourseClazzById(id);
    }

    @Transactional
    @Override
    public boolean insertClazzs(Long courseId, Long[] clazzIds) {
        Long userId = SecurityUtils.getUserId();
        List<CourseClazz> list = new ArrayList<CourseClazz>();
        for (Long clazzId : clazzIds) {
            CourseClazz courseClazz = new CourseClazz();
            courseClazz.setClazzId(clazzId);
            courseClazz.setCourseId(courseId);
            courseClazz.setTeacherId(userId);
            list.add(courseClazz);
        }

        List<StudentClazz> studentClazzLists = studentClazzService.listByClazzId(clazzIds);
        List<Long> studentIds = studentClazzLists.stream().map(StudentClazz::getStudentId).collect(Collectors.toList());
        Course course = courseService.getById(courseId);
        course.setCourseStudentsCount(course.getCourseStudentsCount()+(long) studentIds.size());
        courseService.updateCourse(course);
        courseStudentService.bindStudents(courseId,studentIds);


        return saveBatch(list);
    }

    @Override
    public int removeClazzs(Long courseId, Long[] clazzIds) {
        int count =0;
        for (Long clazzId : clazzIds) {
            boolean remove = remove(new LambdaUpdateWrapper<CourseClazz>().eq(CourseClazz::getClazzId, clazzId).eq(CourseClazz::getCourseId, courseId));
            if(remove){
                count++;
            }
        }
        List<StudentClazz> studentClazzLists = studentClazzService.listByClazzId(clazzIds);
        List<Long> studentIds = studentClazzLists.stream().map(StudentClazz::getStudentId).collect(Collectors.toList());
        Course course = courseService.getById(courseId);
        long courseStudentCount = course.getCourseStudentsCount()-(long) studentIds.size();
        course.setCourseStudentsCount(courseStudentCount<0?0:courseStudentCount);
        courseService.updateCourse(course);
        courseStudentService.unBindStudents(courseId,studentIds);
        return count;
    }
    @Override
    public TeacherInfoVO listTeacherInfo() {
        Long userId = SecurityUtils.getUserId();
        List<CourseClazz> courseClazzes = baseMapper.selectCourseClazzList(new CourseClazz().setTeacherId(userId));
        List<CourseClazzVO> courseTeacherVOS = Binder.convertAndBindRelations(courseClazzes, CourseClazzVO.class);
        TeacherInfoVO teacherInfoVO = new TeacherInfoVO();
        teacherInfoVO.setCourseVOList(courseTeacherVOS);

        List<Long> courseClazzIds = courseClazzes.stream().map(CourseClazz::getId).collect(Collectors.toList());
        List<Lesson> lessonList = lessonService.list(new LambdaUpdateWrapper<Lesson>().eq(Lesson::getStatus, EnumLessonStatus.START.getCode()).eq(Lesson::getTeacherId, userId).in(Lesson::getCourseClazzId, courseClazzIds));
        List<Long> teacherIds = lessonList.stream().map(Lesson::getTeacherId).distinct().collect(Collectors.toList());
        Map<Long, String> sysUserNameMap = sysUserService.selectUserByIds(teacherIds.toArray(new Long[0])).stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getUserName));
        List<LessonVO> lessonVOS = new ArrayList<>();
        for (int i = 0; i < lessonList.size(); i++) {
            LessonVO lessonVO = new LessonVO();
            BeanUtils.copyBeanProp( lessonVO,lessonList.get(i));
            lessonVO.setTeacherName(sysUserNameMap.get(lessonVO.getTeacherId()));
            lessonVOS.add(lessonVO);
        }
        teacherInfoVO.setLessonList(lessonVOS);
        return teacherInfoVO;
    }
}
